package com.huifenqi.smart.controller;

import com.huifenqi.common.HfqResponse;
import com.huifenqi.model.Meter;
import com.huifenqi.smart.service.MeterService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.UUID;

/**
 * @author lisheng
 * @description
 * @date 2018/11/1 17:59
 * @version:
 */
@RestController
@RequestMapping("/smart")
@Slf4j
public class SmartController {

    @Autowired
    private MeterService meterService;


    @PostMapping(value = "/save/meter")
    public HfqResponse saveMeter(@RequestBody Meter meter) {
        log.info("smart save meter service");
        meterService.upsert(meter);
        return HfqResponse.<Meter>builder()
                .code(1)
                .msg("保存电表成功")
                .build();
    }

    @GetMapping(value = "/get/meter/{id}")
    public HfqResponse getMeter(@PathVariable("id") Integer id) {
        log.info("smart get meter service");
        Meter meter = meterService.get(id);
        return HfqResponse.<Meter>builder()
                .code(1)
                .msg("查询电表成功")
                .data(meter)
                .build();
    }

    @RequestMapping(method = RequestMethod.POST, value = "/upload",
            produces = {MediaType.APPLICATION_JSON_UTF8_VALUE},
            consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    @SneakyThrows
    public String upload(@RequestPart(value = "file") MultipartFile file,
                             @RequestParam(value = "fileType") String fileType) {
        long size= file.getSize();
        String contentType= file.getContentType();
        String name = file.getName();
        String orgFilename= file.getOriginalFilename();
        log.info("size: {}",size);
        log.info("contentType: {}",contentType);
        log.info("name: {}",name);
        log.info("orgFilename: {}",orgFilename);

        File dest =   new File("E:/test/upload/"+ UUID.randomUUID().toString());
        file.transferTo(dest);
        return dest.getCanonicalPath();//文件的绝对路径
    }

    @RequestMapping(method = RequestMethod.GET, value = "/download")
    @SneakyThrows
    public ResponseEntity<byte[]> download() {
        byte[] res = getBytes("E:/test/test.txt");
        HttpHeaders headers = new HttpHeaders();
        headers.add("Content-Type", "application/octet-stream");
        headers.add("Connection", "close");
        headers.add("Accept-Ranges", "bytes");
        headers.add("Content-Disposition",
                "attachment;filename=" + new String("test.txt".getBytes("GB2312"), "ISO8859-1"));
        return new ResponseEntity<byte[]>(res, headers, HttpStatus.OK);
    }

    @SneakyThrows
    private byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}
